
package JET.Actions;

import JET.Centers.ControlCenter;
import JET.Scene;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptException;

import org.w3c.dom.*;

/**
 *
 * @author 057Ry
 */
public class RunJavaScriptCodeAction extends Action {

    static final ControlCenter CC = ControlCenter.getInstance();
    String code;
    CompiledScript compiled;
    private Scene scene;

    public RunJavaScriptCodeAction(String name, String code, Scene scene) {
        super(name);
        this.scene = scene;
        this.code = code;
        try {
            this.compiled = ((Compilable) this.scene.SC.getJsEngine()).compile(code);
        } catch (ScriptException ex) { ex.printStackTrace(); }
    }

    public RunJavaScriptCodeAction(Element actionXMLElement) {
        super("RunJavaScriptCodeAction");
        
        NodeList children  = actionXMLElement.getChildNodes();

        for(int i=0; i<children.getLength(); i++) {
            Node node = children.item(i);
            if (node instanceof Element)
            {
                Element elem = (Element)node;

                // Mass
                if (elem.getTagName().equals("name") ) {
                    Text textNode = (Text) elem.getFirstChild();
                    this.setName( textNode.getData().trim() );
                }
                else if (elem.getTagName().equals("code") ) {
                    Text textNode = (Text) elem.getFirstChild();
                    this.code = textNode.getData();
                    try {
                        this.compiled = ((Compilable) scene.SC.getJsEngine()).compile(code);
                    } catch (ScriptException ex) { ex.printStackTrace(); }
                }
            }
        }
    }
    
    @Override
    public void call() {
        try {
            this.compiled.eval(scene.SC.getJsEngine().getContext());
        } catch (ScriptException ex) {
            
            ex.printStackTrace();
        }
    }

    /**
     *
     * @param doc
     * @param cc
     * @return
     */
    @Override
    public Element getXMLRepresentation(Document doc, Scene scene)
    {
        Element rootElement = doc.createElement("action");
        rootElement.setAttribute("class_name", this.getClass().getName());

        rootElement.appendChild(doc.createTextNode("\n"));

        Element nameEl = doc.createElement("name");
        nameEl.appendChild(doc.createTextNode(getName()));
        rootElement.appendChild(nameEl);

        rootElement.appendChild(doc.createTextNode("\n"));

        Element codeEl = doc.createElement("code");
        codeEl.appendChild(doc.createTextNode(this.code));

        rootElement.appendChild(codeEl);

        rootElement.appendChild(doc.createTextNode("\n"));
        return rootElement;
    }

}
